package gson.emlog.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import java.util.UUID;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

import android.content.Context;
import android.content.ContextWrapper;
import android.content.SharedPreferences;
public class Http {
	
	private ArrayList<BasicNameValuePair> pairs = new ArrayList<BasicNameValuePair>();
	private String url;
	
	/**
	 * 
	 * @param context
	 */
	public Http(Context context) {
		ContextWrapper cw = new ContextWrapper(context);
		SharedPreferences settings = cw.getSharedPreferences(Constant.PREFS_NAME, 0);  
		pairs.add(new BasicNameValuePair("rand",UUID.randomUUID().toString().replace("-", "")));
		pairs.add(new BasicNameValuePair(ParamsKey.APP_KEY, settings.getString(Constant.PREFS_KEY_APP_KEY, "")));
		pairs.add(new BasicNameValuePair(ParamsKey.CLIENT_KEY, settings.getString(Constant.PREFS_KEY_CLIENT_KEY,"")));
		this.url = settings.getString(Constant.PREFS_KEY_BLOG_URL, "")+Constant.PREFS_KEY_RPC;
	}
	
	/**
	 * 
	 * @param url
	 */
	public Http(String url) {
		pairs.add(new BasicNameValuePair("rand",UUID.randomUUID().toString().replace("-", "")));
		this.url = url;
	}
	
	/**
	 * 
	 * @param action
	 * @param parmas
	 * @return
	 */
	public Result post(String action,HashMap<String, Object> parmas) {
		HttpPost post = new HttpPost(this.url);
		Result  result = new Result();
		if (parmas != null) {
			Set<String> keys = parmas.keySet();
			for (Iterator<String> i = keys.iterator(); i.hasNext();) {
				String key = (String) i.next();
				pairs.add(new BasicNameValuePair(key, parmas.get(key).toString()));
			}
		}
		
		if(action != null)
			pairs.add(new BasicNameValuePair(ParamsKey.ACTION, action));
	
		UrlEncodedFormEntity p_entity;
		try {
			p_entity = new UrlEncodedFormEntity(pairs, "utf-8");
			post.setEntity(p_entity);
			result = send(post);
		} catch (UnsupportedEncodingException e) {
			result.setStatus(false);
			result.setData(e.getMessage());
			return result;
		}
		return  result;
	}
	
	/**
	 * 
	 * @param action
	 * @return
	 */
	public Result post(String action) {
		return post(action,null);
	}
	
	public Result post() {
		return post(null,null);
	}

	/**
	 * 
	 * @param requet
	 * @return
	 */
	private Result send(HttpUriRequest requet) {
		HttpClient client = new DefaultHttpClient();

		Result result = new Result();
		try {
			HttpResponse response = client.execute(requet);
			int code = response.getStatusLine().getStatusCode();
			if(code == 200){
				HttpEntity entity = response.getEntity();
				InputStream content = entity.getContent();
				String returnConnection = convertStreamToString(content);
				returnConnection = returnConnection.substring(returnConnection.indexOf("{"),returnConnection.lastIndexOf("}")+1);
				JSONObject json = (JSONObject) JSONValue.parse(returnConnection);
				if((Boolean) json.get("status")){
					result.setStatus(true);
				}else{
					result.setStatus(false);
				}
				result.setData(json.get("data"));
			}else{
				result.setStatus(false);
				result.setData(code);
			}
		} catch (ClientProtocolException e) {
			result.setStatus(false);
			result.setData("协议错误!"+e.getMessage());
		} catch (IOException e) {
			result.setStatus(false);
			result.setData("网络异常，无法解析："+e.getMessage());
		}catch (Exception e) {
			result.setStatus(false);
			result.setData("error:"+e.getMessage());
		}
		return result;
	}

	/**
	 * 
	 * @param is
	 * @return
	 */
	private String convertStreamToString(InputStream is) {
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuilder sb = new StringBuilder();
		String line = null;
		try {
			while ((line = reader.readLine()) != null) {
				sb.append(line);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return sb.toString().trim();
	}
}
